<template>
	<view>
		<lsj-upload ref="lsjUpload" :height="'100%'" :option="option" @uploadEnd="onUploadEnd" @change="onChange"
			:size="maxSize" :instantly="true">
			<slot></slot>
		</lsj-upload>
	</view>
</template>

<script>
export default {
	name: "file-upload",
	data() {
		return {
			fileMap: new Map(),
			option: {
				url:this.define.baseURL + '/xf-api/xf-im-platform/third/file/upload',
				name: 'file',
				header: {
					'X-Access-Token':uni.getStorageSync('token')
				}
			}
		}
	},
	props: {
		maxSize: {
			type: Number,
			default: 1
		},
		onBefore: {
			type: Function,
			default: null
		},
		onSuccess: {
			type: Function,
			default: null
		},
		onError: {
			type: Function,
			default: null
		}
	},
	methods: {
		show() {
			this.$refs.lsjUpload.show();
		},
		hide() {
			this.$refs.lsjUpload.hide();
		},
		onUploadEnd(item) {
			 this.onChange(item.file)
			 // let file = this.fileMap.get(item.path);
			 let file = item.file;
			if (item.type == 'fail') {
				this.onError(file)
				return;
			}
			let res = JSON.parse(item.responseText);
			if (res.code == 200) {
				// 上传成功
				this.onOk(file, res.data);
			} else {
				// 上传失败
				this.onError(file, res);
			}
		},
		onChange(files) {
			if (!files.size) {return;}
			this.onBefore && this.onBefore(files)
			// files.forEach((file, name) => {
			// 	if (!this.fileMap.has(file.path)) {	
			// 		this.onBefore && this.onBefore(file)
			// 		this.fileMap.set(file.path, file);	
			// 	}
			// })
		},
		onOk(file, res) {
			console.log(file,res)
			this.fileMap.delete(file.path);
			this.$refs.lsjUpload.clear(file.name);
			this.onSuccess && this.onSuccess(file, res);
		},
		onFailed(file, res) {
			this.fileMap.delete(file.path);
			this.$refs.lsjUpload.clear(file.name);
			this.onError && this.onError(file, res);
		},
		refreshToken() {
			// return new Promise((resolve, reject) => {
			// 	let loginInfo = uni.getStorageSync('loginInfo')
			// 	uni.request({
			// 		method: 'PUT',
			// 		url: this.define.baseURL + '/refreshToken',
			// 		header: {
			// 			refreshToken: loginInfo.refreshToken
			// 		},
			// 		success: (res) => {
			// 			resolve(res.data);
			// 		},
			// 		fail: (res) => {
			// 			reject(res);
			// 		}
			// 	})
			// })
		}
	}

}
</script>

<style></style>